package org.zheng.shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.zheng.shop.dto.CarouselDTO;
import org.zheng.shop.security.UserDetailsImpl;
import org.zheng.shop.service.CarouselService;

import java.util.List;
import java.util.Map;

/**
 * 轮播图控制器
 */
@RestController
@RequestMapping("/api/carousel")
public class CarouselController {
    
    @Autowired
    private CarouselService carouselService;
    
    /**
     * 获取所有启用的轮播图（公开接口）
     */
    @GetMapping
    public ResponseEntity<List<CarouselDTO>> getEnabledCarousels() {
        try {
            List<CarouselDTO> carousels = carouselService.getEnabledCarousels();
            return ResponseEntity.ok(carousels);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 管理员获取所有轮播图
     */
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getAllCarousels() {
        try {
            List<CarouselDTO> carousels = carouselService.getAllCarousels();
            return ResponseEntity.ok(carousels);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取轮播图列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取轮播图
     */
    @GetMapping("/admin/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getCarouselById(@PathVariable Long id) {
        try {
            CarouselDTO carousel = carouselService.getCarouselById(id);
            if (carousel != null) {
                return ResponseEntity.ok(carousel);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "获取轮播图失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建轮播图
     */
    @PostMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createCarousel(@RequestBody CarouselDTO carouselDTO, 
                                          Authentication authentication) {
        try {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            CarouselDTO createdCarousel = carouselService.createCarousel(carouselDTO, userDetails.getId());
            return ResponseEntity.ok(createdCarousel);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "创建轮播图失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新轮播图
     */
    @PutMapping("/admin/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateCarousel(@PathVariable Long id, 
                                          @RequestBody CarouselDTO carouselDTO) {
        try {
            CarouselDTO updatedCarousel = carouselService.updateCarousel(id, carouselDTO);
            if (updatedCarousel != null) {
                return ResponseEntity.ok(updatedCarousel);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "更新轮播图失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除轮播图
     */
    @DeleteMapping("/admin/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteCarousel(@PathVariable Long id) {
        try {
            boolean deleted = carouselService.deleteCarousel(id);
            if (deleted) {
                return ResponseEntity.ok(Map.of("message", "轮播图删除成功"));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "删除轮播图失败: " + e.getMessage()));
        }
    }
    
    /**
     * 切换轮播图启用状态
     */
    @PatchMapping("/admin/{id}/toggle")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> toggleCarouselStatus(@PathVariable Long id) {
        try {
            CarouselDTO updatedCarousel = carouselService.toggleCarouselStatus(id);
            if (updatedCarousel != null) {
                return ResponseEntity.ok(updatedCarousel);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(Map.of("error", "切换状态失败: " + e.getMessage()));
        }
    }
}
